<?php


namespace Rebuild\HttpServer;


use FastRoute\Dispatcher;

use Hyperf\Utils\Context;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Rebuild\HttpServer\Contract\CoreMiddlewareInterface;

use Rebuild\HttpServer\Router\Dispatched;
use Rebuild\HttpServer\Router\DispatherFactory;

class CoreMiddleware implements CoreMiddlewareInterface
{
    protected Dispatcher $dispatcher;

    public function __construct(DispatherFactory $dispatherFactory)
    {
        $this->dispatcher = $dispatherFactory->getDispatcher('http');
    }

    public function dispatch(ServerRequestInterface $request): ServerRequestInterface
    {
        $method = $request->getMethod();
        $uri = $request->getUri()->getPath();
        $routeInfo = $this->dispatcher->dispatch($method, $uri);
        $dispatched = new Dispatched($routeInfo);
        return Context::set(ServerRequestInterface::class, $request->withAttribute(\Hyperf\HttpServer\Router\Dispatched::class, $dispatched));
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // TODO: Implement process() method.
    }
}